<?php

namespace App\Services;

use App\Common\Libs\Pagination;
use App\Consts\ExceptionCodeConst;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Validator;

class BaseService extends Service
{

    /** @var null $validator */
    public $validator = null;

    /** @var null $repository */
    protected $repository = null;

    /**
     * get pagination
     * @param array $paginationParams
     * @return Pagination
     */
    public function getPagination($paginationParams = [])
    {
        return (new Pagination())->getPagination($paginationParams);
    }

    /**
     * set pagination
     * @param Builder $provider
     * @param array|Pagination $paginationParams
     * @return Builder
     */
    public function setPagination(Builder $provider, $paginationParams = [])
    {
        if ($paginationParams instanceof  Pagination) {
            $pagination = $paginationParams;
            $pagination->page--;
        } else {
            $pagination = $this->getPagination($paginationParams);
        }

        $offset = $pagination->page * $pagination->pageSize;

        return $provider->offset($offset)->take($pagination->pageSize);
    }

    /**
     * validate data
     * @param array $data
     * @param array $rule
     * @param array $message
     * @return \Illuminate\Http\JsonResponse|bool
     */
    public function validate($data = [], $rule = [], $message = [])
    {
        $this->validator = Validator::make($data, $rule, $message);
        if ($this->validator->fails()) {
            return apiShutdown($this->validator->errors()->first(), ExceptionCodeConst::ILLEGAL_PARAMETER);
        }
        return true;
    }

    /**
     * 错误中断返回
     * @param $message
     * @param int $code
     */
    public function throwError($message, $code = ExceptionCodeConst::CODE_FAIL)
    {
        return apiShutdown($message, $code);
    }

    /**
     * 错误信息返回
     * @param string $message
     * @param int $code
     * @param array $data
     * @return array
     */
    public function error($message = '', $code = ExceptionCodeConst::CODE_FAIL, $data = [])
    {
        $message = $message ?: lang('Missing Params');
        return ["code" => strval($code), "msg" => $message, "data" => $data];
    }

}
